#include "DBObject.h"

namespace SQLDoc
{
	DBObject::DBObject(int objectType, QString name /*= QString("")*/, int id /*= -1*/) 
		: m_childItems(QList<DBObject*>())
	{
		m_objectType = objectType;
		m_parentItem = 0x00000000;
		m_id = id;
		m_name = name;
		m_checked = Qt::Unchecked;
	}

	DBObject::~DBObject(void)
	{
		qDeleteAll(m_childItems);
	}

	QString DBObject::name() const 
	{ 
		return m_name;
	}

	void DBObject::setName(QString val) 
	{ 
		m_name = val; 
	}

	QString DBObject::comment() const 
	{ 
		return m_comment;
	}

	void DBObject::setComment(QString val) 
	{ 
		m_comment = val; 
	}

	Qt::CheckState DBObject::checked() const 
	{
		return m_checked; 
	}

	void DBObject::setChecked(Qt::CheckState val)
	{ 
		m_checked = val;

		if (m_checked != Qt::PartiallyChecked)
		{
			if (!m_childItems.empty())
			{
				int count = m_childItems.count();

				for (int i = 0; i < count; i++)
				{
					m_childItems.value(i)->setChecked(m_checked);
				}
			}
		}
	}

	void DBObject::verifyCheckedState(Qt::CheckState childState)
	{
		m_checked = childrenCheckState();

		if (m_parentItem)
			m_parentItem->verifyCheckedState(m_checked);
	}

	Qt::CheckState DBObject::childrenCheckState(void)
	{
		int count = m_childItems.count();
		Qt::CheckState state;

		if (m_childItems.empty())
			return m_checked;

		if (count == 1)
			return m_childItems.value(0)->childrenCheckState();

		state = m_childItems.value(0)->childrenCheckState();
		for (int i = 1; i < count; i++)
		{
			if (state != m_childItems.value(i)->childrenCheckState())
				return Qt::PartiallyChecked;
		}
		return state;
	}

	int DBObject::id() const 
	{ 
		return m_id;
	}

	void DBObject::setId(int val) 
	{ 
		m_id = val;
	}

	int DBObject::objectType() const 
	{ 
		return m_objectType;
	}

	DBObject *DBObject::childItem(int row) 
	{ 
		return m_childItems.value(row); 
	}

	QList<DBObject*>& DBObject::childItems() 
	{ 
		return m_childItems;
	}

	DBObject *DBObject::parentItem() const 
	{
		return m_parentItem;
	}

	int DBObject::childCount() const 
	{ 
		return m_childItems.count(); 
	}

	void DBObject::addChild(DBObject *child) 
	{ 
		child->setParentItem(this);
		child->setChecked(m_checked);
		m_childItems.append(child);
	}

	void DBObject::setParentItem(DBObject *parent)
	{
		m_parentItem = parent; 
	};
}
